package com.imooc.mall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.encoder.QRCode;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.filter.UserFilter;
import com.imooc.mall.model.dao.CartMapper;
import com.imooc.mall.model.dao.OrderItemMapper;
import com.imooc.mall.model.dao.OrderMapper;
import com.imooc.mall.model.dao.ProductMapper;
import com.imooc.mall.model.pojo.Order;
import com.imooc.mall.model.pojo.OrderItem;
import com.imooc.mall.model.pojo.Product;
import com.imooc.mall.model.request.CreateOrder;
import com.imooc.mall.model.vo.CartVo;
import com.imooc.mall.model.vo.OrderItemVO;
import com.imooc.mall.model.vo.OrderVO;
import com.imooc.mall.service.CartService;
import com.imooc.mall.service.OrderService;


import com.imooc.mall.service.UserService;
import com.imooc.mall.util.OrderCodeFactory;
import com.imooc.mall.util.QRCodeGenerator;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private UserService userService;

    @Value("${file.upload.ip}")
    String ip;

    // 生成订单号
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateOrder createOrder){
        // 拿到用户的ID
        Integer userId = UserFilter.currentUser.getId();

        // 从购物车中查找已勾选的商品
//        List<Cart> carts = cartMapper.selectedCart(userId, 1);
//        本来我的想法是直接在购物车中直接查询selected= 1 就可以了 现在感觉好像还是少了什么东西//少了购物车封装的vo对象

        List<CartVo> cartVoList = cartService.list(userId);
        ArrayList<CartVo> CartVosTemp = new ArrayList<CartVo>();
        for (int i = 0; i < cartVoList.size(); i++) {
            CartVo cartVo =  cartVoList.get(i);
            if (cartVo.getSelected().equals(Constant.Check.selected)){
                CartVosTemp.add(cartVo);
            }
        }
        cartVoList = CartVosTemp;

        // 如果勾选的商品为空 报错
        if (CollectionUtils.isEmpty(cartVoList)){
            throw new ImoocMallException(ImoocMallExceptionEnum.CART_EMPTY);
        }

        //判断商品是否存在，上下架状态，库存
        vaildProductStockAndStatus(cartVoList);

        //把购物车对象转换成订单Item 对象
        List<OrderItem> orderItems = cartVolistToOrderItemList(cartVoList);
        // 对商品总扣库存
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            int stock = product.getStock() - orderItem.getQuantity();
            // 加入的时候有库存，但是下单的时候就被别人买走了
            if (stock < 0){
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ENOUGH);
            }
            product.setStock(stock);
            productMapper.updateByPrimaryKeySelective(product);
        }

        //把购物车中的已勾选商品删除
        clearCart(cartVoList);

        //生成订单
        Order order = new Order();

        //生成订单号
        String orderNo = OrderCodeFactory.getOrderCode(Long.valueOf(userId));
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setTotalPrice(totalprice(orderItems));
        // 收件人信息
        order.setReceiverName(createOrder.getReceiverName());
        order.setReceiverMobile(createOrder.getReceiverMobile());
        order.setReceiverAddress(createOrder.getReceiverAddress());
        // 订单属性状态赋值
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setPostage(0);
        order.setPaymentType(1);
        // 插入到Order表中
        orderMapper.insertSelective(order);

        //循环保存每一个商品到Order_item表
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            orderItem.setOrderNo(order.getOrderNo());
            orderItemMapper.insertSelective(orderItem);
        }

        //把结果返回
        return orderNo;

    }

    private Integer totalprice(List<OrderItem> orderItems) {
        Integer totalPrice = 0;
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            totalPrice += orderItem.getTotalPrice();
        }
        return totalPrice;
    }

    private void clearCart(List<CartVo> cartVoList) {
        for (int i = 0; i < cartVoList.size(); i++) {
            CartVo cartVo = cartVoList.get(i);
            cartMapper.deleteByPrimaryKey(cartVo.getId());
        }
    }

    private List<OrderItem> cartVolistToOrderItemList(List<CartVo> cartVoList) {
        ArrayList<OrderItem> arrayList = new ArrayList<OrderItem>();
        for (int i = 0; i < cartVoList.size(); i++) {
            CartVo cartVo = cartVoList.get(i);
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(cartVo.getProductId());
            orderItem.setProductName(cartVo.getProductName());
            // 记录商品快照信息
            orderItem.setProductImg(cartVo.getProductImage());
            orderItem.setUnitPrice(cartVo.getPrice());
            orderItem.setQuantity(cartVo.getQuantity());
            orderItem.setTotalPrice(cartVo.getTotalPrice());
            arrayList.add(orderItem);
        }
        return arrayList;
    }

    private void vaildProductStockAndStatus(List<CartVo> cartVoList) {
        for (int i = 0; i < cartVoList.size(); i++) {
            CartVo cartVo = cartVoList.get(i);
            Product product = productMapper.selectByPrimaryKey(cartVo.getProductId());
            // 判断商品是否存在，商品是否上架
            if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE))
            {
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE);
            }

            // 如果要添加的数量大于数据库的数量是本能成功的
            if (cartVo.getQuantity() > product.getStock()){
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ENOUGH);
            }
        }

    }

    @Override
    public OrderVO detail(String orderNo){
        // 为了防止订单ID出现所以要用订单的名字来镜进行传值
        Order order = orderMapper.selectByOrderName(orderNo);
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ORDER);
        }

        // 订单存在，需要判断所属
        Integer userId = UserFilter.currentUser.getId();
        if (!order.getUserId().equals(userId)){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }

        OrderVO orderVO = getOrderVO(order);
        return orderVO;
    }

    private OrderVO getOrderVO(Order order) {
        OrderVO orderVO = new OrderVO();
        // 获取订单对应的Order对应的属性
        BeanUtils.copyProperties(order,orderVO);
        // 查询出这个OrderItem 对象OrderVo为Order
        List<OrderItem> orderItems = orderItemMapper.selectByOrderNo(order.getOrderNo());
        // 创建一个可以存放OrderItemVO的对象列表
        List<OrderItemVO> orderItemVOList = new ArrayList<>();
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            OrderItemVO orderItemVO = new OrderItemVO();
            BeanUtils.copyProperties(orderItem,orderItemVO);
            orderItemVOList.add(orderItemVO);
        }
        orderVO.setOrderItemVOList(orderItemVOList);
        // 通过表结构中的内容来对数据进行修改
        orderVO.setOrderStatusName(Constant.OrderStatusEnum.codeOf(orderVO.getOrderStatus()).getValue());
        return orderVO;
    }

    @Override
    public PageInfo list(Integer pageNum, Integer pageSize){
        List<OrderVO> orderVO = new ArrayList<>();

        List<Order> orders = orderMapper.selectByOrderUserId(UserFilter.currentUser.getId());
        if (orders == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ON_ORDER);
        }
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            orderVO.add(getOrderVO(order)) ;
        }
        Page<Object> objects = PageHelper.startPage(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo(orderVO);
//        pageInfo.setList(orderVO);
        return pageInfo;
    }

    @Override
    public void cancel(String orderNo){
        Order order = orderMapper.selectByOrderName(orderNo);
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ORDER);
        }
        Integer id = UserFilter.currentUser.getId();
        if (!order.getUserId().equals(id)){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }
        // 查看当前的订单状态
        // 订单存在，需要进行判断状态
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())){
            order.setOrderStatus(Constant.OrderStatusEnum.CANCELED.getCode());
            order.setEndTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else {
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_STATUS);
        }
    }

    @Override
    public String qrcode(String orderNo){
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        String address = ip+":"+request.getLocalPort();
        String payUrl = "http://"+address +"/pay?orderNo="+orderNo;
        // 每个订单的支付二维码都是不一样的
        try {
            QRCodeGenerator.generateQRCodeImage(payUrl,350,350,Constant.FILE_UPLOAD_DIR+orderNo+".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 生成images这样子的地址
        String pngAddress = "http://"+address+"/images/"+orderNo +".png";
        return pngAddress;
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize){
        List<OrderVO> orderVOList = new ArrayList<>();
        Page<Object> objects = PageHelper.startPage(pageNum, pageSize);
        List<Order> orders = orderMapper.selectByAllForAdmin();
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            orderVOList.add(getOrderVO(order));
        }

        PageInfo<OrderVO> orderPageInfo = new PageInfo<>(orderVOList);
        orderPageInfo.setList(orderVOList);
        return orderPageInfo;
    }


    @Override
    public void pay(String orderNo){
        // 为了防止订单ID出现所以要用订单的名字来镜进行传值
        Order order = orderMapper.selectByOrderName(orderNo);
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ORDER);
        }
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode()))
        {
            order.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
            order.setPayTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else{
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_STATUS);
        }
    }

    // 发货
    @Override
    public void deliver(String orderNo){
        // 为了防止订单ID出现所以要用订单的名字来镜进行传值
        Order order = orderMapper.selectByOrderName(orderNo);
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ORDER);
        }
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.PAID.getCode()))
        {
            order.setOrderStatus(Constant.OrderStatusEnum.DELIVERED.getCode());
            order.setDeliveryTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else{
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_STATUS);
        }
    }


    // 发货
    @Override
    public void finish(String orderNo){
        // 为了防止订单ID出现所以要用订单的名字来镜进行传值
        Order order = orderMapper.selectByOrderName(orderNo);
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ORDER);
        }
        // 如果是普通用户，就要校验订单的所属 如果不是管理员 判断订单里面的userId == 用户的UserID
        if (!userService.checkAdminRole(UserFilter.currentUser) && !order.getUserId().equals(UserFilter.currentUser.getId())){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }
        // 有两种情况就是证明他现在的自己在操作自己的订单 一种是管理员在操作
        // 发货后可以完结订单
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.DELIVERED.getCode()))
        {
            order.setOrderStatus(Constant.OrderStatusEnum.FINISHED.getCode());
            order.setEndTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else{
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_STATUS);
        }
    }


}